package com.yuantu.judiciary.model.word;

import lombok.Data;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kgwei
 * 元素的组合，暂时只支持图片和表格组合，一个图片一个表格
 */
@Data
public class WordCombine implements WordElement {

    private List<WordElement> elements;

    public static WordCombine defaultCombine(String imageUrl, ImageSourceType imageSourceType, List<String> tableTitles, List<List<String>> tableData, boolean imageLeft) {
        WordCombine wordCombine = new WordCombine();
        List<WordElement> elements = new ArrayList<>();
        if (imageLeft) {
            elements.add(WordImage.defaultWordImage(imageUrl, imageSourceType, "png"));
        }
        String[][] array = new String[tableData.size()][];
        for (int i = 0; i < tableData.size(); i++) {
            List<String> row = tableData.get(i);
            array[i] = row.toArray(new String[0]);
        }
        elements.add(WordTable.defaultTableWithTitle(tableTitles.toArray(new String[0]), array));
        if (!imageLeft) {
            elements.add(WordImage.defaultWordImage(imageUrl, imageSourceType, "png"));
        }
        wordCombine.setElements(elements);
        return wordCombine;
    }

    public static WordCombine combineImageAndTable(WordImage wordImage, WordTable wordTable, boolean imageLeft) {
        WordCombine wordCombine = new WordCombine();
        List<WordElement> elements = new ArrayList<>();
        if (imageLeft) {
            elements.add(wordImage);
            elements.add(wordTable);
        } else {
            elements.add(wordTable);
            elements.add(wordImage);
        }
        wordCombine.setElements(elements);
        return wordCombine;
    }

    public static WordCombine combineElements(List<WordElement> elements) {
        WordCombine wordCombine = new WordCombine();
        wordCombine.setElements(elements);
        return wordCombine;
    }

    @Override
    public WordElementType getElementType() {
        return WordElementType.COMBINE;
    }

    @Override
    public void addElement(XWPFDocument document) {
        //创建一个一行两列的表格
        XWPFTable table = document.createTable(1, 2);
        table.removeBorders();
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        CTTblWidth tblWidth = tblPr.addNewTblW();
        tblWidth.setW(BigInteger.valueOf(5000));
        tblWidth.setType(STTblWidth.PCT);

        XWPFTableRow row = table.getRow(0);
        setCellWidthAndAlignment(row.getCell(0), 2500);
        setCellWidthAndAlignment(row.getCell(1), 2500);

        int index = 0;
        for (WordElement element: elements) {
            XWPFTableCell cell = row.getCell(index);
            if (element.getElementType() == WordElementType.IMAGE) {
                ((WordImage) element).imageBuild(cell.getParagraphArray(0).createRun());
            } else if (element.getElementType() == WordElementType.TABLE) {
                WordTable wordTable = (WordTable) element;
                XWPFParagraph tableParagraph = cell.getParagraphArray(0);
                XmlCursor cursor = tableParagraph.getCTP().newCursor();
                // 在光标处插入一个新的表格
                XWPFTable contentTable = cell.insertNewTbl(cursor);
                createEmptyTable(contentTable.getCTTbl());
                createTableRow(contentTable, wordTable);
            }
            index++;
        }
        document.createParagraph();
    }

    /**
     * 给表格创建固定行和列
     * @param table .
     * @param wordTable .
     */
    private void createTableRow(XWPFTable table, WordTable wordTable) {
        List<WordTableRow> wordTableRows = wordTable.getTableRows();
        for(int i = 0; i < wordTable.getRows(); ++i) {
            XWPFTableRow tabRow = table.getRow(i) == null ? table.createRow() : table.getRow(i);
            wordTableRows.get(i).rowBuild(tabRow);
            List<WordTableCell> wordTableCells = wordTableRows.get(i).getCells();
            for(int k = 0; k < wordTable.getCols(); ++k) {
                XWPFTableCell cell = tabRow.getCell(k);
                if (cell == null) {
                    cell = tabRow.createCell();
                }
                WordTableCell wordTableCell = wordTableCells.get(k);
                wordTableCell.setAlignment(ParagraphAlignment.CENTER);
                wordTableCell.cellBuild(cell);
            }
        }
    }

    private void createEmptyTable(CTTbl table) {
        CTTblPr tblpro = table.addNewTblPr();
        tblpro.addNewTblW().setW(BigInteger.valueOf(5000L));
        tblpro.getTblW().setType(STTblWidth.PCT);
        CTTblBorders borders = tblpro.addNewTblBorders();
        borders.addNewBottom().setVal(STBorder.SINGLE);
        borders.addNewInsideH().setVal(STBorder.SINGLE);
        borders.addNewInsideV().setVal(STBorder.SINGLE);
        borders.addNewLeft().setVal(STBorder.SINGLE);
        borders.addNewRight().setVal(STBorder.SINGLE);
        borders.addNewTop().setVal(STBorder.SINGLE);
    }

    // 设置单元格宽度，并设置水平和垂直居中
    private void setCellWidthAndAlignment(XWPFTableCell cell, int widthPct) {
        // 设置单元格相对宽度
        CTTcPr tcPr = cell.getCTTc().addNewTcPr();
        CTTblWidth cellWidth = tcPr.addNewTcW();
        // 宽度的百分比
        cellWidth.setW(BigInteger.valueOf(widthPct));
        // 设置为百分比
        cellWidth.setType(STTblWidth.PCT);
        // 设置垂直居中
        CTVerticalJc vAlign = tcPr.addNewVAlign();
        vAlign.setVal(STVerticalJc.CENTER);
        // 创建段落并设置水平居中
        XWPFParagraph paragraph = cell.addParagraph();
        // 水平居中
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        // 移除默认的段落
        cell.removeParagraph(0);
    }
}
